//
//  DASearchBookDetailViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/5/9.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DASearchBookDetailViewController.h"
#import "DABorrowBookView.h"
#import "DAloginPersonalInformation.h"
#import "DASameReaderView.h"
#import "DAHomePageViewController.h"
#import "DATabBarViewController.h"
#import "DASimilarBook.h"
#import "Utility.h"
#import "DAOtherPersonalViewController.h"

@interface DASearchBookDetailViewController () <viewDisappear,DAImageViewDelegate, DASimilarBookDelegate, DASameReaderView>/** 图书上放钉子的后面的白色view*/

{
    //MBProgressHUD *hud;
}
@property (nonatomic, strong) UIView *whiteBackRoundView;
/** 钉子所在的灰色view*/
@property (nonatomic, strong) UIView *grayNailView;
/** 图书的width约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookBackViewWidth;
/** 图书的height约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookBackViewHeight;
/** 图书后面的白色边框view*/
@property (weak, nonatomic) IBOutlet UIView *bookBackView;
/** scrollView*/
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/** 书的描述*/
@property (weak, nonatomic) IBOutlet DALabel *bookDescription;
/** 书描述下方的线*/
@property (weak, nonatomic) IBOutlet UILabel *bookDescriptionBottomLine;
/** 书的名字*/
@property (weak, nonatomic) IBOutlet DALabel *bookNameLabel;

/** 读过的头像下方的线*/
@property (weak, nonatomic) IBOutlet UILabel *userImageBottomLine;
/** 在scrollView上的view*/
@property (weak, nonatomic) IBOutlet UIView *onTheScrollViewBackView;
/** 弹出借书的view*/
@property (nonatomic, strong) DABorrowBookView *borrowBookView;
/** 灰色萌版的view*/
@property (nonatomic, strong) UIView *grayBackView;
/** scrollViewHeight约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewHeight;
/** 图书详情的view*/
@property (weak, nonatomic) IBOutlet UIView *bookDetailView;
/** 图书详情height约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookDetailViewHeight;
/** 类似图书的label*/
@property (weak, nonatomic) IBOutlet UILabel *otherBookLabel;
/** 类似图书的image*/
@property (strong, nonatomic) IBOutlet UIImageView *otherBookImage;
/** 图书描述label的height约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookDescriptionHeight;
@property (nonatomic, copy) NSString *str;
/** 用来保存图书边框的frame*/
@property (nonatomic, assign) CGRect bookBackViewFrame;
/** 用来保存图书image的frame*/
@property (nonatomic, assign) CGRect bookImageFrame;
/** 用于遮挡图书的view*/
@property (nonatomic, strong) UIImageView *coverView;
/** 图书边框view的副本*/
@property (nonatomic, strong) UIView *bookBackViewCopyView;
/** 图书image的副本*/
@property (nonatomic, strong) UIImageView *bookImageCopyView;
@property (nonatomic, assign) CGRect borrowBookViewFromFrame;
@property (nonatomic, assign) CGRect borrowBookViewToFrame;
@property (nonatomic, assign) CGRect coverViewFromFrame;
@property (nonatomic, assign) CGRect coverViewToFrame;

@property (weak, nonatomic) IBOutlet UILabel *bookType;
@property (weak, nonatomic) IBOutlet UILabel *bookSource;
/** 评分view*/
@property (weak, nonatomic) IBOutlet DARateView *rateView;

@property (weak, nonatomic) IBOutlet UILabel *readBookLabel;
@property (nonatomic, strong) DAloginPersonalInformation *personalInformation;

@property (weak, nonatomic) IBOutlet DASameReaderView *sameReaderView;


@property (weak, nonatomic) IBOutlet DASimilarBook *similarBook;

@end

@implementation DASearchBookDetailViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /** TODO: 图书的大小进行屏幕适配*/
    if (SCREENWIDTH < 375) {
        self.bookBackViewWidth.constant = 160 * SCREENWIDTH / 375;
        self.bookBackViewHeight.constant = 220 * SCREENWIDTH / 375;
    }
    self.tabBarController.tabBar.translucent = NO;
   // [self bookDetailViewSetting];
   // [self updateViewConstraints];
    
   // [self getRateViewAndOtherUserReadBook];
    
    // 准备数据
    [self prepareData];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.bookImage.pushPin.frontView.hidden = YES;
    self.bookImage.pushPin.bubbleColor = [UIColor colorWithHexString:backGroundColor];
    _bookImage = nil;
    [_bookImage removeFromSuperview];
}
#pragma mark - 数据准备
- (void)prepareData{
    //[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *isLoading = NSLocalizedString(@"isLoading", nil);
    [SVProgressHUD showWithStatus:isLoading];
//    self.bookDetailView.hidden = YES;
    NSString *url = DABookDetailURL;
    NSDictionary *dic = @{@"bookID": self.bookID,
                          @"userID": self.userID};
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSDictionary class]]) {
                DASearchBookDetailModel *detailBookModel = [[DASearchBookDetailModel alloc]init];
                self.bookDetailModel = [detailBookModel dataTransformModelWith:result[@"result"]];
                [self bookDetailViewSetting];
                [self getRateViewAndOtherUserReadBook];
                [self creatBookImage];
                [self finishLoadDataMBProgress];
                [self updateViewConstraints];
                NSLog(@"图书编号: %@", result[@"result"][@"bookPrivate"]);
        } else {
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
            }
            NSLog(@"DABookDetailURL:数据异常。");
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark -setBookIMage
- (void)creatBookImage{
    _bookImage = [[DAImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 70, 20  , 140, 170)];
    _bookImage.delegate = self;
    
    UIView *bookCover = [[UIView alloc]initWithFrame:CGRectMake(0 , 0, _bookImage.frame.size.width, _bookImage.frame.size.height)];
    bookCover.backgroundColor = [UIColor supportGreenColor];
    DALabel *bookCoverName = [[DALabel alloc]initWithFrame:CGRectMake(5, 20, bookCover.frame.size.width -10, bookCover.frame.size.height - 40)];
    [bookCoverName setText:self.bookDetailModel.bookName fitToContent:YES];
    [bookCoverName setTextColor:[UIColor whiteColor]];
    bookCoverName.font = [UIFont systemFontOfSize:12];
    bookCoverName.verticalAlignment = VerticalAlignmentMiddle;
    bookCoverName.textAlignment = NSTextAlignmentCenter;
    [bookCover addSubview:bookCoverName];
    
    UIImage *image = [self.view makeImageWithView:bookCover];
    [_bookImage sd_setImageWithURL:[NSURL URLWithString:self.bookDetailModel.bookImage] placeholderImage:image];
    
  //  [_bookImage sd_setImageWithURL:[NSURL URLWithString:self.bookDetailModel.bookImage] placeholderImage:[UIImage imageNamed:@"Java.jpg"]];
    [_bookImage showOnView:self.view];
    self.bookBackView.backgroundColor = [UIColor clearColor];
}

#pragma mark - bookDetailViewSetting
- (void)bookDetailViewSetting{
    self.str = self.bookDetailModel.bookIntro;
    [self.bookDescription setText:self.str fitToContent:YES];
    self.bookDescription.font = [UIFont systemFontOfSize:12];
    self.onTheScrollViewBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.bookDescriptionBottomLine.backgroundColor =[UIColor groupTableViewBackgroundColor];
    self.userImageBottomLine.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.bookBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.scrollView.delaysContentTouches = YES;
    self.scrollView.canCancelContentTouches = NO;
    NSString *bookType = NSLocalizedString(@"bookType", nil);
    self.bookType.text = [NSString stringWithFormat:@"%@ :%@", bookType,self.bookDetailModel.bookTypeName];
    NSString *bookSource = NSLocalizedString(@"bookSource", nil);
    self.bookSource.text = [NSString stringWithFormat:@"%@: %@",bookSource,self.bookDetailModel.bookSourceName];
    self.bookType.font = [UIFont systemFontOfSize:12];
    self.bookSource.font = [UIFont systemFontOfSize:12];
    self.bookType.textColor = [UIColor colorWithHexString:borrowTimeColor];
    self.bookSource.textColor = [UIColor colorWithHexString:borrowTimeColor];
    NSString *sameReader = NSLocalizedString(@"readTheBookPeople", nil);
    self.readBookLabel.text = sameReader;
    self.readBookLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    NSString *otherBook = NSLocalizedString(@"bookSimilar", nil);
    self.otherBookLabel.text = otherBook;
    self.otherBookLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    [self.bookNameLabel setText:self.bookDetailModel.bookName fitToContent:YES];
    //self.bookNameLabel.text = self.bookDetailModel.bookName;
    self.bookNameLabel.textColor = [UIColor colorWithHexString:bookNameColor];
    self.bookDescription.textColor = [UIColor colorWithHexString:bookNameColor];
    self.otherBookLabel.font = [UIFont systemFontOfSize:12];
    self.readBookLabel.font = [UIFont systemFontOfSize:12];
}
#pragma mark - 更新约束
- (void)updateViewConstraints{
    
    CGFloat height = [self heightWithText:self.str Width:[UIScreen mainScreen].bounds.size.width - 80 Font:12];
    CGFloat bookNameHeight = [self heightWithText:self.bookDetailModel.bookName Width:self.bookDetailView.frame.size.width - 40 Font:15];
    self.bookDetailViewHeight.constant = 280 + height + bookNameHeight;
    self.scrollViewHeight.constant = 300 + self.bookBackViewHeight.constant + 40 + height + bookNameHeight;
  
    [super updateViewConstraints];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self updateViewConstraints];
}
#pragma mark -BorrowAnimation
- (void)borrowAnimation{
     self.borrowBookView = [[DABorrowBookView alloc]initWithFrame:CGRectMake(20, self.view.bounds.size.height + 100, self.view.frame.size.width - 40, 340) numberArray:self.bookDetailModel.bookPrivate ];
    self.borrowBookView.delegate = self;
    [_bookImage.backView addSubview:self.borrowBookView];
    
    self.borrowBookViewToFrame = CGRectMake(20, _bookImage.frame.size.height - 70, self.view.frame.size.width - 40, 340);
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.borrowBookView.frame = self.borrowBookViewToFrame;
    } completion:^(BOOL finished) {
        
    }];
}
#pragma mark - cardAnimation
- (void)cardAnimation{
    self.coverView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"book_card@3x"]];
    [self.view addSubview:self.coverView];
    DALabel *borrowTimeLabel = [[DALabel alloc]initWithFrame:CGRectMake(20, 10, 100, 20)];
    NSString *bookNumber = NSLocalizedString(@"bookNumber", nil);
    [borrowTimeLabel setText:bookNumber];
    borrowTimeLabel.font = [UIFont systemFontOfSize:12];
    borrowTimeLabel.textColor = [UIColor colorWithHexString:userNameColor];
    [self.coverView addSubview:borrowTimeLabel];
    self.coverView.frame = CGRectMake(20, self.view.bounds.size.height + 100, self.borrowBookView.frame.size.width -10, 35);
    self.coverViewToFrame = CGRectMake(20, _bookImage.frame.size.height -30 ,self.borrowBookView.frame.size.width -10, 35);
    [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.4 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.coverView.frame = self.coverViewToFrame;
    } completion:^(BOOL finished) {
        
    }];
    [self.onTheScrollViewBackView bringSubviewToFront:self.coverView];
}
#pragma mark - DAImageView协议方法
- (void)viewDragFinished{
    [self borrowAnimation];
    [self cardAnimation];
}
- (void)viewWillReturn{
    [self borrowBookViewWillDisapper];
}
#pragma mark - borrowBookView消失方法
- (void)borrowBookViewWillDisapper{
    [UIView animateWithDuration:0.5 animations:^{
        self.borrowBookView.frame = CGRectMake(20, self.view.bounds.size.height + 100, self.view.frame.size.width - 40, 320 * WIDTHTOFIT5s);
        self.coverView.frame = CGRectMake(20, self.view.bounds.size.height + 100, self.view.frame.size.width - 40, 320);
    } completion:^(BOOL finished) {
        [self.borrowBookView removeFromSuperview];
        [self.coverView removeFromSuperview];
        [self.bookImage viewReturn];
    }];
}
#pragma mark - DABorrowBookView协议方法
- (void)viewDisapper{
    [self borrowBookViewWillDisapper];
}
#pragma mark - 借书的协议方法
- (void)toBorrowBookWithTime:(NSString *)borrowDuration Privacy:(NSString *)privacy BookNumber:(NSString *)bookNumber{
    NSString *isChooseBorrowTime = NSLocalizedString(@"isChooseBorrowTime",nil );
    NSString *isChooseBookNumber = NSLocalizedString(@"isChooseBookNumber", nil);
    if (borrowDuration == nil) {
        [SVProgressHUD showErrorWithStatus:isChooseBorrowTime];
    }if (bookNumber == nil) {
        [SVProgressHUD showErrorWithStatus:isChooseBookNumber];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self finishLoadDataMBProgress];
    });
    // 借阅期 和图书编号 都不能为空
    if (borrowDuration != nil && bookNumber != nil) {
        //[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD show];
        NSString *url = DABorrowBookURL;
        NSDictionary *dic = @{@"userID": self.userID,
                              @"bookID": self.bookDetailModel.bookID,
                              @"borrowDuration": borrowDuration,
                              @"addTimeline": privacy,
                              @"bookPrivate": bookNumber};
        NSLog(@"%@", dic);
        NSString *isBorrowSuccess = NSLocalizedString(@"isBorrowSuccess", nil);
        NSString *isBorrowFailed = NSLocalizedString(@"isBorrowFailed", nil);
        [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
            
            if (result) {
                if ([result isKindOfClass:[NSDictionary class]] && [result[@"result"] isEqualToString:@"true"]) {
                    NSLog(@"借阅成功");
                    // [self loadMBProgress:@"借阅成功"];
                    [SVProgressHUD showSuccessWithStatus:isBorrowSuccess];
                    /** 延时*/
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        // 发送通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"back" object:nil];
                        if (self.isHomePageEnter) {
                            // 发送让主页面刷新的通知
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"isBorrowSuccessful" object:nil];
                        }
                        
                        if (self.isScanning) {
                            [self dismissViewControllerAnimated:YES completion:nil];
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectIndex" object:nil];
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"isBorrowSuccessful" object:nil];
                        }
                        [self.navigationController popViewControllerAnimated:YES];
                        [self finishLoadDataMBProgress];
                    });
                }else{
                    
                    if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                        [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                    }
                    if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                        [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                    }if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection] ) {
                        [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                    }
                    
                    else{
                        [SVProgressHUD showErrorWithStatus:isBorrowFailed];
                    }
                    
//                    NSLog(@"借阅失败");
//                    [SVProgressHUD showErrorWithStatus:@"借阅失败"];
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        [self finishLoadDataMBProgress];
//                    });
                }
            } else {
                NSLog(@"DABorrowBookURL:数据异常。");
                [self finishLoadDataMBProgress];
            }
            
        }];
        [self borrowBookViewWillDisapper];
    }
}
#pragma mark - 获取用户id
- (void)getUserID{
    /** 解档*/
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    self.personalInformation = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.bookDetailView = nil;
    self.bookImageCopyView = nil;
    [self.view removeFromSuperview];
}
#pragma mark - 获取评分以及阅读过此书的人和类似的图书
- (void)getRateViewAndOtherUserReadBook{
    /** 评分*/
    NSString *rate = self.bookDetailModel.bookRate;
    [self.rateView rateNum:rate.integerValue];
    [self.rateView setNeedsDisplay];
    self.sameReaderView.delegate = self;
    [self.sameReaderView creatReaderUserImageWithArray:self.bookDetailModel.bookSameReader];
    self.similarBook.delegate = self;
    [self.similarBook creatSimilarBookImageWithArray:self.bookDetailModel.similiarBook];
}

#pragma mark - 类似图书的delegate方法
- (void)similarBookClick:(NSInteger)index{
    self.bookID = self.bookDetailModel.similiarBook[index][@"bookID"];
    self.bookImage.pushPin.frontView.hidden = YES;
    self.bookImage.pushPin.bubbleColor = [UIColor colorWithHexString:backGroundColor];
    self.bookImage.image = nil;
    [self.bookImage removeFromSuperview];
    [self prepareData];
}
#pragma mark - 相同阅读者的delegate方法
- (void)sameReaderView:(NSInteger)index{
    NSString *userId = self.bookDetailModel.bookSameReader[index][@"userID"];
    self.bookImage.pushPin.frontView.hidden = YES;
    self.bookImage.pushPin.bubbleColor = [UIColor colorWithHexString:backGroundColor];
    self.bookImage.image = nil;
    [self.bookImage removeFromSuperview];
    [self turnPersonal:userId];
}
#pragma mark - 加载菊花
- (void)loadMBProgress:(NSString *)str{
    [SVProgressHUD showInfoWithStatus:str];
//    hud = [[MBProgressHUD alloc]initWithView:self.view];
//    hud.dimBackground = NO;
//    /** 设置加载文字*/
//    hud.labelText = str;
//    hud.minShowTime = 1;
//    hud.activityIndicatorColor = [UIColor themeWhiteColor];
//    hud.labelColor = [UIColor themeWhiteColor];
//    hud.mode = MBProgressHUDModeText;
//    [[UIApplication sharedApplication].keyWindow addSubview:hud];
//    // [self.view addSubview:self.hud];
//    [hud showAnimated:NO whileExecutingBlock:^{
//    } completionBlock:^{
//        [hud removeFromSuperview];
//         hud = nil;
//    }];
}

#pragma mark - 跳转到其他个人页面
- (void)turnPersonal:(NSString *)userID{
    DAOtherPersonalViewController *otherPersonal = [self.storyboard instantiateViewControllerWithIdentifier:@"OTHERPERSONAL"];
    otherPersonal.hidesBottomBarWhenPushed = YES;
    otherPersonal.otherUserID = userID;
    [self.navigationController pushViewController:otherPersonal animated:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
